package com.yuan.yblog.portal.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yuan.yblog.common.api.CommonResult;
import com.yuan.yblog.portal.aop.annotation.SlidingWindowLimiter;
import com.yuan.yblog.portal.enums.LimitType;
import com.yuan.yblog.portal.pojo.VO.UserCollectionVO;
import com.yuan.yblog.portal.service.UserCollectionService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * (UserCollection)表控制层
 * @since 2023-12-03 14:21:18
 */
@RestController
@RequestMapping("/userCollection")
@Tag(name = "用户收藏（collection）接口")
public class UserCollectionController {
    @Autowired
    private UserCollectionService userCollectionService;

    @Operation(summary = "获取自己的文章收藏列表")
    @GetMapping("/MyCollection")
    public CommonResult<IPage<UserCollectionVO>> selectAll(
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Long pageNumber,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "7") Long pageSize,
            @Parameter(description = "排序字段") @RequestParam(required = false) String sortKey,
            @Parameter(description = "排序方式，是否降序") @RequestParam(required = false) Boolean isDesc) {
        IPage<UserCollectionVO> result = userCollectionService.list(pageNumber,pageSize,sortKey,isDesc);
        return CommonResult.success(result);
    }

    @Operation(summary = "用户【操作】收藏文章")
    @PostMapping("/insert")
    public CommonResult<Long> insert(@Parameter(description = "收藏提交实体") @RequestBody UserCollectionVO userCollectionVO) {
        // 插入
        Long id = userCollectionService.insert(userCollectionVO);
        if(id==null) {
            return CommonResult.failed("操作失败");
        }
        else {
            return CommonResult.success(id,"收藏成功，收藏项id："+id);
        }
    }

    @Operation(summary = "用户【取消】收藏")
    @DeleteMapping("/delete")
    public CommonResult<Integer> delete(@RequestParam("postIds") List<Long> postId) {
        int row = userCollectionService.delete(postId);
        return CommonResult.success(row,"删除数目=" + row);
    }

    @SlidingWindowLimiter(key = "collect", windowSize = 120, windowTimeRange = 60, limitType = LimitType.IP)
    @Operation(summary = "判断当前用户是否已收藏该文章")
    @GetMapping("/isCollected")
    public CommonResult<Long> isCollected(@Parameter(description = "文章id") @RequestParam("postId") Long postId) {
        Boolean flag = userCollectionService.isCollected(postId);
        if(flag) {
            return CommonResult.success(1L,"本文已收藏");
        }
        else {
            return CommonResult.failed("没有收藏");
        }
    }

}

